package org.jiang.springbootdemo.demos.web.component;

import org.jiang.springbootdemo.demos.web.interceptor.BeanMethodInterceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;

public class LogicInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /*
        postProcessBeforeInstantiation返回不为null，postProcessProperties不会执行
        postProcessBeforeInstantiation返回null + postProcessAfterInstantiation返回true，postProcessProperties会执行
     */
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
        System.out.print("beanName:" + beanName + "执行..postProcessBeforeInstantiation\n");
        if (beanClass == Bean.class) {
            //利用cglib其生成动态代理
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(beanClass);
            enhancer.setCallback(new BeanMethodInterceptor());
            Bean bean = (Bean) enhancer.create();
            System.out.print("返回动态代理\n");
            return bean;
        }
        return null;
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        System.out.print("beanName:" + beanName + "执行..postProcessAfterInstantiation\n");
        // 会影响postProcessProperties是否执行，返回false不执行
        return true;
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        System.out.print("beanName:" + beanName + "执行..postProcessProperties\n");
        if (bean instanceof Bean) {
            //修改bean中name 的属性值
            PropertyValue value = pvs.getPropertyValue("name");
            System.out.print("修改之前name的value是：" + value.getValue() + "\n");
            value.setConvertedValue("我修改啦");
            return pvs;
        }
        return pvs;
    }

    //************************************** BeanPostProcessor **********************************************
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.print("beanName:" + beanName + "执行..postProcessBeforeInitialization\n");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.print("beanName:" + beanName + "执行..postProcessAfterInitialization\n");
        return bean;
    }
}
